﻿using AiBLSmartEdu.Module.Auth.API.Configurations;
using AiBLSmartEdu.Module.Auth.API.Interfaces;
using FrameworkCore.Extensions;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace AiBLSmartEdu.Module.Auth.API.Services;

public class TokenService : ITokenService
{
    public Task<string> BuildAsync(IEnumerable<Claim> claims, JwtSettings options, bool isRefreshToken = false)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SecurityKey));
        var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var refreshExpires = "exp";

        DateTime expires;
        string timestamp;

        if (isRefreshToken)
        {
            expires = DateTime.UtcNow.AddSeconds(options.RefreshExpiresSeconds);
            timestamp = expires.ToUnixTimestampSeconds().ToString();
            claims = claims.Append(new Claim(refreshExpires, timestamp)).ToList();
        }
        else
        {
            expires = DateTime.UtcNow.AddSeconds(options.ExpireSeconds);
            timestamp = expires.ToUnixTimestampSeconds().ToString();
            claims = claims.Append(new Claim(refreshExpires, timestamp)).ToList();
        }

        var token = new JwtSecurityToken(
            issuer: options.Issuer,
            audience: options.Audience,
            claims: claims,
            notBefore: DateTime.UtcNow,
            expires: expires,
            signingCredentials: signingCredentials
        );

        return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token));
    }

    public JwtSecurityToken Decode(string jwtToken)
    {
        var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
        var jwtSecurityToken = jwtSecurityTokenHandler.ReadJwtToken(jwtToken);
        return jwtSecurityToken;
    }
}
